package com.lenovo.mobile.platform

import com.android.build.gradle.AppExtension
import com.squareup.javapoet.FieldSpec
import com.squareup.javapoet.JavaFile
import com.squareup.javapoet.TypeSpec
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.gradle.api.Plugin
import org.gradle.api.Project
import java.io.File
import javax.lang.model.element.Modifier

/**
 * @author     : RuiO
 * date        : 2023/7/19
 * description :
 */
class MobilePlatformPlugin : Plugin<Project> {
    var oriJsonConfig = ""
    override fun apply(project: Project) {
        generateTask(project)
    }

    private fun generateTask(project: Project){

        val client = OkHttpClient()
        //获取配置信息定义
        val request = Request.Builder().url("http://10.120.133.127:1024/dev-api/openapi/pack/userPack/sitemap/1").build()
        val response:Response = client.newCall(request).execute()
        val body = response.body

        oriJsonConfig = body?.string()?:""
        println("获取平台化配置信息：$oriJsonConfig")
        project.afterEvaluate {
            val appExtension = project.extensions.getByType(AppExtension::class.java)
            appExtension.configAndroidAppName()
            appExtension.applicationVariants.all {
                val variantName = name
                generateBuildConfigProvider.configure {
                    doLast {
                        doGenerateJavaSourceFile(project, variantName)
                    }
                }
            }
        }
    }
    private fun doGenerateJavaSourceFile(project: Project, buildType:String){
        val config = "\"" + oriJsonConfig?.replace("\"", "\\\"") + "\""

        println("配置已经成功获取，开始新增java类，配置信息：$oriJsonConfig")
        println("配置已经成功获取，开始新增java类，写入配置信息：$config")
        println("当前编译类型：$buildType")

        val configField = FieldSpec.builder(String::class.java, "LenovoConfig", Modifier.PUBLIC,Modifier.STATIC,Modifier.FINAL).initializer(config).build()
        val configClass = TypeSpec
                .classBuilder("MobilePlatform")
            .addModifiers(Modifier.PUBLIC)
            .addField(configField)
            .build()
        val javaFile = JavaFile.builder("com.marion.zeus", configClass).build()

        val file = File(project.projectDir.path + "/build/generated/source/buildConfig/" + buildType+ "/")
        javaFile.writeTo(file)
        println("新增java类MobilePlatform完毕--继续其他编译")

    }

    private fun AppExtension.configAndroidAppName(){
        defaultConfig{
            manifestPlaceholders["appName"] = "联想插件"
        }
    }

}
